package com.simon.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simon.train.common.dto.MemberTicketDto;
import com.simon.train.common.util.SnowUtil;
import com.simon.train.common.vo.PageVO;
import com.simon.train.member.domain.Ticket;
import com.simon.train.member.domain.TicketExample;
import com.simon.train.member.dto.TicketQueryDto;
import com.simon.train.member.mapper.TicketMapper;
import com.simon.train.member.vo.TicketQueryVO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TicketService {

    private static final Logger LOG = LoggerFactory.getLogger(TicketService.class);

    @Resource
    private TicketMapper ticketMapper;

    /**
     * 会员购买车票后新增保存
     * @param memberTicketDto
     */
    public void SaveTicket(MemberTicketDto memberTicketDto){
        Ticket ticket = BeanUtil.copyProperties(memberTicketDto, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        DateTime time = DateTime.now();
        ticket.setCreateTime(time);
        ticket.setUpdateTime(time);
        ticketMapper.insert(ticket);

    }

    public PageVO<TicketQueryVO> QueryTicketList(TicketQueryDto ticketQueryDto){
        TicketExample ticketExample = new TicketExample();
        ticketExample.setOrderByClause("id desc");
        TicketExample.Criteria criteria = ticketExample.createCriteria();
        if(ObjUtil.isNotNull((ticketQueryDto.getMemberId()))){
            criteria.andMemberIdEqualTo(ticketQueryDto.getMemberId());
        }
        LOG.info("当前请求的页码：{}", ticketQueryDto.getPage());
        LOG.info("每页条数：{}", ticketQueryDto.getPageSize());

        PageHelper.startPage(ticketQueryDto.getPage(),ticketQueryDto.getPageSize());
        List<Ticket> ticketList = ticketMapper.selectByExample(ticketExample);

        PageInfo<Ticket> pageInfo = new PageInfo<>(ticketList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<TicketQueryVO> lists = BeanUtil.copyToList(ticketList, TicketQueryVO.class);
        PageVO<TicketQueryVO> pageVO = new PageVO<>();
        pageVO.setList(lists);
        pageVO.setTotal(pageInfo.getTotal());

        return pageVO;
    }

    public void deleteTicket(Long id) {
        ticketMapper.deleteByPrimaryKey(id);
    }
}
